<?php
//APP图片操作
namespace App\Http\Controllers\App;
use App\Http\Controllers\App\BaseController as Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class ImgController extends Controller
{
    //图片上传
    public function upload(Request $request)
    {
        if($_FILES['thumb']['size'] == 0 || $_FILES['thumb']['size']>1024*1024) {
            return show(201, '请上传1M以内的图片');
        }
        $rules = [
            'thumb'=>'required|image',
            'token'=>'required|string',
            'device_id'=>'required|string',
        ];
        $message = [
            'thumb.*' =>   '请上传图片',
            'token.*' =>   '请传入令牌',
            'device_id.*'=>'请传入设备ID',
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(201,$validator->errors()->first());
        }
        $type = $request->file('thumb')->getClientOriginalExtension();
        if (!in_array($type,['jpg','jpeg','png'])){
            return show(201,'请上传png|jpg|jpeg格式的图片');
        }
        //验证令牌
        $user  = $this->CheckThisUser($request->token,$request->device_id);
        if(!$user){
            return show(202,'无效token');
        }
        if($user->role == "-1"){
            $path = "user_{$user->id}/shop";
        }else{
            $path = "clerks_{$user->id}/shop_{$user->shop_id}";
        }
        $path = $request->file('thumb')->storePublicly($path);
        return show(200,'上传成功','/storage/'. $path);
    }
}
